<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Api\RoleRequest;
use App\Transformers\RoleTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Spatie\Permission\Models\Role;
use stdClass;

class RoleController extends BaseController
{
    /**
     * 所有角色
     */
    public function roles()
    {
        $roles = Role::all();
//        响应生成器
        return $this->response->collection($roles,new RoleTransformer());
    }

    /**
     * 角色级别
     */
    public function level()
    {
        $level = array(
            $this->getObj(5,"超级"),
            $this->getObj(1,"一级"),
            $this->getObj(2,"二级")
        );
        return $level;
    }
    protected function getObj($value, $label)
    {
        $obj= new stdClass();
        $obj->value = $value;
        $obj->label = $label;
        return $obj;
    }

    /**
     * 角色列表
     */
    public function index()
    {
        $roles = Role::paginate(20);  // 分页
//        响应生成器
        return $this->response->paginator($roles,new RoleTransformer());
    }
    /**
     * 添加角色
     */
    public function store(RoleRequest $request)
    {
        $str = Str::random(6);
        $request->offsetSet('name', $str);
        $request->offsetSet('guard_name', 'api');
//        批量赋值
        Role::create($request->all());

        return $this->response->created();
    }

    /**
     * 更新角色
     */
    public function update(RoleRequest $request, Role $role)
    {
//        批量赋值
        $role->update($request->all());
        return $this->response->noContent();
    }

    /**
     * 删除角色
     */
    public function destroy(Role $role)
    {
        $role->delete();
        return $this->response->noContent();
    }

    /**
     * 给角色添加权限
     */
    public function addPerm(Role $role,Request $request)
    {
        $request->validate([
            'permissions' => 'required|array'
        ],[
            'permissions.required' => '权限不能为空',
            'permissions.array' => '权限必须是一个数组',
        ]);
        $role->givePermissionTo($request->input('permissions'));
        return $this->response->noContent();
    }
}
